﻿using EagleProject.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace EagleProject.Controllers
{
    public class MyController : Controller
    {
        protected UserInformation GetUserInformation()
        {
            var data = Session["User"];
            if (data == null) return null;
            else return data as UserInformation;
        }

        protected void SetUserInformation(UserInformation info)
        {
            Session.Add("User", info);
        }

        protected bool IsAuthenticated()
        {
            var data = Session["User"];
            return data != null;
        }

        private bool IsThisRole(params string[] roleName)
        {
            if (!IsAuthenticated()) return false;
            string type = GetUserInformation().UserType;
            foreach (var role in roleName) { if (type.Contains(role.ToLower())) { return true; } }
            return false;
        }

        private bool IsThisRole(string roleName)
        {
            if (!IsAuthenticated()) return false;
            string type = GetUserInformation().UserType;
            return type.Contains(roleName.ToLower());
        }

        public bool IsAdmin()
        {
            return IsThisRole("admin");
        }

        public bool IsOfficer()
        {
            return IsThisRole("admin", "officer");
        }

        public bool IsPartner()
        {
            return IsThisRole("admin", "officer", "partner");
        }

        public bool IsConsultant()
        {
            return IsThisRole("admin", "consultant");
        }

        public bool IsAgent()
        {
            return IsThisRole("admin", "consultant", "agent");
        }

        public bool IsHumanResource()
        {
            return IsThisRole("admin", "humanresource");
        }

        public bool IsSubscriber()
        {
            return IsThisRole("subscriber");
        }

        private string GetUploadDirectory(string directoryOnServer)
        {
            return Server.MapPath(directoryOnServer);
        }

        protected bool IsUploadFile()
        {
            return Request.Files.Count != 0;
        }

        private string GenerateRandomFileName(string directory, string extension)
        {
            var fileName = System.Guid.NewGuid().ToString().Replace("-", "") + extension;
            var abs = Path.Combine(directory, fileName);
            while (System.IO.File.Exists(abs))
            {
                fileName = System.Guid.NewGuid().ToString().Replace("-", "") + extension;
                abs = Path.Combine(directory, fileName);
            }
            return fileName;
        }

        private string HandleFileUpload(string directoryOnServer, int fileNumber)
        {
            var file = Request.Files[fileNumber];
            if (file != null && file.ContentLength > 0)
            {
                var uploadFileName = Path.GetFileName(file.FileName);
                var extension = Path.GetExtension(uploadFileName);

                var newFileName = GenerateRandomFileName(GetUploadDirectory(directoryOnServer), extension);
                var path = Path.Combine(GetUploadDirectory(directoryOnServer), newFileName);

                file.SaveAs(path);

                return directoryOnServer + '/' + newFileName;
            }
            else return null;
        }

        protected string HandleFileUpload(string directoryOnServer)
        {
            return HandleFileUpload(directoryOnServer, 0);
        }

        protected List<string> HandleFileUploads(string directoryOnServer)
        {
            List<string> listUrl = new List<string>();
            int numberOfFile = Request.Files.Count;
            for (int i = 0; i < numberOfFile; i++)
            {
                string url = HandleFileUpload(directoryOnServer, i);
                if (url != null)
                {
                    listUrl.Add(url);
                }
            }
            return listUrl;
        }

        protected string HandleFileUploadsToJson(string directoryOnServer)
        {
            string[] datas = HandleFileUploads(directoryOnServer).ToArray();
            string json = new JavaScriptSerializer().Serialize(datas);
            return json;
        }

        protected int GetIntParam(string param)
        {
            try
            {
                int data = Int32.Parse(Request.Params[param]);
                return data;
            }
            catch
            {
                return -1;
            }
        }

        protected string GetStringParam(string param)
        {
            return Request.Params[param];
        }

        protected ActionResult RedirectToHome()
        {
            return RedirectToAction("Index", "Home");
        }

        protected ActionResult RedirectToAccessDenied()
        {
            return RedirectToAction("AccessDenied", "Home");
        }

        protected ActionResult RedirectToLogin(string returnUrl)
        {
            return RedirectToAction("Login", "User", new { ReturnUrl = returnUrl });
        }

        protected ActionResult RedirectToControlPanel()
        {
            if (!IsAuthenticated()) { return RedirectToAction("Index", "Home"); }
            return RedirectToAction("ControlPanel", "User");
        }

        protected const int NumberOfRecordPerPage = 10;

        public static SelectList ListMarialStatus = new SelectList(new List<ListItem> { 
                new ListItem {Text = "Single", Value = "Single"}, 
                new ListItem {Text = "Married", Value = "Married"}, 
                new ListItem {Text = "Seperated", Value = "Seperated"}, 
                new ListItem {Text = "Divorced", Value = "Divorced"}, 
                new ListItem {Text = "Widow", Value = "Widow"}, 
                new ListItem {Text = "Widower", Value = "Widower"},
            });

        public static SelectList ListTitleName = new SelectList(
           new List<ListItem> { 
                new ListItem{Text = "Mr.", Value = "Mr."} ,
                new ListItem{Text = "Mrs.", Value = "Mrs."} ,                
                new ListItem{Text = "Ms.", Value = "Ms."} ,
                new ListItem{Text = "Prof.", Value = "Prof."} ,
                new ListItem{Text = "Dr.", Value = "Dr."} ,
                new ListItem{Text = "Gen.", Value = "Gen."} ,
                new ListItem{Text = "Rep.", Value = "Rep."} ,
                new ListItem{Text = "Sen.", Value = "Sen."} ,
                new ListItem{Text = "St.", Value = "St."} 
            });

        public static SelectList ListEduction = new SelectList(
                 new List<ListItem> {
                    new ListItem { Text = "University", Value = "University" },
                    new ListItem { Text = "College", Value = "College" },
                    new ListItem { Text = "Polytechnics", Value = "Polytechnics" },
                    new ListItem { Text = "Secondary School", Value = "Secondary School" }
            });

        public static SelectList ListCard = new SelectList(
                new List<ListItem> {
                    new ListItem { Text = "Regular Card", Value = "1" },
                    new ListItem { Text = "Process Regular Card", Value = "2" },
                    new ListItem { Text = "Special Card", Value = "3" },
                    new ListItem { Text = "First Class Citizen Card", Value = "4" }
            });

        public static string GetGender(bool sex)
        {
            return sex ? "Male" : "Female";
        }

        public static string CardNameOfType(int? type)
        {
            // ko sd duoc LinQ, chat hieu vi sao
            if (!type.HasValue) return "Unknown";
            foreach (ListItem item in ListCard.Items)
            {
                if (Int32.Parse(item.Value) == type.Value)
                {
                    return item.Text;
                }
            }
            return "Unknown";
        }
    }
}
